package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/ServletDemo1")
public class ServletDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.通过响应对象写出提示信息
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        writer.write("欢迎来到网站，您最后访问时间为：<br/>");

        //2.创建Cookie对象，用于记录最后访问时间
        Cookie cookie = new Cookie("time",System.currentTimeMillis()+"");

        //3.设置最大存活时间  以秒为单位
        cookie.setMaxAge(3600);
        
        //4.将cookie对象添加客户端
        resp.addCookie(cookie);
        //5.获取cookie
        Cookie[] arr = req.getCookies();
        for (Cookie c : arr) {
            if("time".equals(c.getName())){
                //6.获取cookie对象value，进行写出
                String value = c.getValue();
                //设置时间格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
               //value是字符，所以转化long，在转化date，在进行格式化，写出
                writer.write(sdf.format(new Date(Long.parseLong(value))));
            }
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
